package com.tsd.system.controller;

import cn.hutool.db.Entity;
import com.alibaba.fastjson.JSON;
import com.tsd.CommonMsgNameConstants;
import com.tsd.CommonParamNameConstants;
import com.tsd.common.controller.BaseController;
import com.tsd.core.constants.Constants;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.datasource.DataSourceInitService;
import com.tsd.core.datasource.DataSourceUtils;
import com.tsd.core.utils.ExceptionUtil;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.HttpUtil;
import com.tsd.core.utils.JdbcUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.system.entity.SysAccountSet;
import com.tsd.system.entity.SysAccountSetExt;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.service.SysAccountSetService;
import com.tsd.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tsd.core.constants.Constants.STATE_DB_NOT_CREATED;
import static com.tsd.core.datasource.DataSourceContextHolder.DEFAULT_ACCOUNT_SET_SID;

/**
 * 描述：SysAccountSet系统账套 控制层
 *
 * @author huawei
 * @date 2021/09/02 21:46:17
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
@Api(tags = "sys_account_set-系统账套", description = "系统账套的API描述")
public class SysAccountSetController extends BaseController {

    public static final Logger LOGGER = LoggerFactory.getLogger(SysAccountSetController.class);

    @Resource
    private SysAccountSetService sysAccountSetService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private DataSourceInitService dataSourceInitService;

    @ApiOperation(value = "根据sid获取系统账套", notes = "根据sid获取系统账套")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "系统账套sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/getSysAccountSetBySid.action", method = RequestMethod.POST)
    public HttpResult<Object> getSysAccountSetBySid() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, CommonParamNameConstants.SID);
            super.checkEmpty(sid, CommonMsgNameConstants.EMPTY_MSG_SID);
            SysAccountSetExt sysAccountSet = sysAccountSetService.queryBySid(sid);
            hr.setData(sysAccountSet);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "测试数据库连接", notes = "测试数据库连接")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "系统账套sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/testConnection.action", method = RequestMethod.POST)
    public HttpResult<Object> testConnection() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, CommonParamNameConstants.SID);
            super.checkEmpty(sid, CommonMsgNameConstants.EMPTY_MSG_SID);
            SysAccountSet o = sysAccountSetService.queryBySid(sid);
            super.checkEmpty(o, CommonMsgNameConstants.EMPTY_MSG_ACCOUNT);
            super.checkEmpty(o.getDriver(), CommonMsgNameConstants.EMPTY_MSG_DRIVER);
            super.checkEmpty(o.getDb_url(), CommonMsgNameConstants.EMPTY_MSG_DB_URL);
            super.checkEmpty(o.getDb_user_name(), CommonMsgNameConstants.EMPTY_MSG_DB_USER_NAME);
            super.checkEmpty(o.getDb_password(), CommonMsgNameConstants.EMPTY_MSG_DB_USER_PASSWORD);
            Connection conn = JdbcUtil.getConnection(o.getDriver(), o.getDb_url(), o.getDb_user_name(), o.getDb_password());
            JdbcUtil.releaseConnection(conn);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e, "1");
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除系统账套", notes = "根据id删除系统账套")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "系统账套sids", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteSysAccountSets.action", method = RequestMethod.POST)
    public HttpResult<Object> deleteSysAccountSets() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get(CommonParamNameConstants.SIDS);
            super.checkEmpty(sids, CommonMsgNameConstants.EMPTY_MSG_SIDS);
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            sysAccountSetService.deleteSysAccountSets(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "保存系统账套", notes = "保存系统账套，具有id值则更新，没有id值则新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "系统账套", required = true, paramType = "body", dataType = "SysAccountSet")
    })
    @ResponseBody
    @RequestMapping(value = "/saveSysAccountSet.action", method = RequestMethod.POST)
    public HttpResult<Object> saveSysAccountSet() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String json = JSON.toJSONString(map);
            SysAccountSetExt t = JSON.parseObject(json, SysAccountSetExt.class);
            sysAccountSetService.saveSysAccountSet(t, opUser);
            if (STATE_DB_NOT_CREATED == t.getState()) {
                try {
                    //建库不影响前端执行逻辑
                    sysAccountSetService.createDataBase(t, false);
                } catch (Exception e) {
                    LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
                }
            }
            Entity entity = DataSourceUtils.getAccountSetBySid(DataSourceContextHolder.getMasterDataSource(), t.getSid());
            dataSourceInitService.initDataSource(entity);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "保存系统账套的属性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "系统账套", required = true, paramType = "body", dataType = "SysAccountSet")
    })
    @ResponseBody
    @RequestMapping(value = "/saveSysAccountSetAttribute.action", method = RequestMethod.POST)
    public HttpResult<String> saveSysAccountSetAttribute() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String json = JSON.toJSONString(map);
            SysAccountSetExt t = JSON.parseObject(json, SysAccountSetExt.class);
            sysAccountSetService.saveSysAccountSetAttribute(t, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询系统账套", notes = "分页查询系统账套")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findSysAccountSets.action", method = RequestMethod.POST)
    public HttpResult<Object> findSysAccountSets() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyIntegerValue(map, params, CommonParamNameConstants.DR, true, 0);
            HlpUtils.copyStringValue(map, params, CommonParamNameConstants.SEARCH_VALUE, false, true);
            HlpUtils.copyIntegerValue(map, params, CommonParamNameConstants.STATE, false, null);
            HlpUtils.copyStringValue(map, params, CommonParamNameConstants.VERSION, false, false);
            HlpUtils.copyDateRangeValue(map, params, CommonParamNameConstants.EXPIRED_DATE, false);
            PageBean page = new PageBean(map);
            List<SysAccountSetExt> list = sysAccountSetService.findSysAccountSets(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "根据系统账套sid创建数据库", notes = "根据系统账套sid创建数据库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "账套sid", required = true, paramType = "body", dataType = "SysAccountSet")
    })
    @ResponseBody
    @RequestMapping(value = "/createDataBase.action", method = RequestMethod.POST)
    public HttpResult<String> createDataBase() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String account_set_sid = HttpUtil.getAccountSet(request);
            String loginId = opUser.getLogin_id();
            String password = HlpUtils.getString(map, CommonParamNameConstants.PASSWORD);
            Map<String, Object> loginParams = new HashMap<>(2);
            loginParams.put(CommonParamNameConstants.LOGIN_ID, loginId);
            loginParams.put(CommonParamNameConstants.PASSWORD, password);
            SysUserExt user = sysUserService.loginUser(loginParams);
            super.checkEmpty(user, CommonMsgNameConstants.ERROR_MSG_PASSWORD);
            if (DEFAULT_ACCOUNT_SET_SID.equals(account_set_sid)) {
                String sid = HlpUtils.getString(map, CommonParamNameConstants.SID);
                SysAccountSetExt t = sysAccountSetService.queryBySid(sid);
                super.checkEmpty(t, CommonMsgNameConstants.EMPTY_MSG_ACCOUNT);
                if (t.getState() == Constants.STATE_DB_CREATING) {
                    return HttpResult.procError(CommonMsgNameConstants.ERROR_MSG_ACCOUNT_RESETING);
                }
                t.setState(STATE_DB_NOT_CREATED);
                t.setCreate_begin(new Date());
                //先更新状态后进行重置，异步处理，前端再调用状态检查接口获取是否重置完毕。
                sysAccountSetService.saveSysAccountSet(t, opUser);
                try {
                    //建库不影响前端执行逻辑
                    sysAccountSetService.createDataBase(t, true);
                } catch (Exception e) {
                    LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
                }
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                return HttpResult.procError(CommonMsgNameConstants.ERROR_MSG_NO_PERMISSION);
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "重置系统账套主账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "系统账套", required = true, paramType = "body", dataType = "SysAccountSet")
    })
    @ResponseBody
    @RequestMapping(value = "/resetSysAccountSetAdminUser.action", method = RequestMethod.POST)
    public HttpResult<String> resetSysAccountSetAdminUser() {
        DataSourceContextHolder.setDataSourceType(null);
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, CommonParamNameConstants.SID);
            String password = HlpUtils.getString(map, CommonParamNameConstants.PASSWORD);
            super.checkEmpty(sid, CommonMsgNameConstants.EMPTY_MSG_SID);
            super.checkEmpty(password, CommonMsgNameConstants.EMPTY_MSG_PASSWORD);
            if (DEFAULT_ACCOUNT_SET_SID.equals(sid)) {
                return HttpResult.procError(CommonMsgNameConstants.NOT_SUPPORT_OPERATION);
            }
            SysAccountSetExt o = sysAccountSetService.queryBySid(sid);
            super.checkEmpty(o, CommonMsgNameConstants.EMPTY_MSG_ACCOUNT);
            try {
                Connection conn = JdbcUtil.getConnection(o.getDriver(), o.getDb_url(), o.getDb_user_name(), o.getDb_password());
                JdbcUtil.releaseConnection(conn);
            } catch (Exception e) {
                return HttpResult.procError(CommonMsgNameConstants.ERROR_MSG_ACCOUNT_CONNECT + e.getMessage());
            }
            DataSourceContextHolder.setDataSourceType(o.getSid());
            HttpResult<String> httpResult = sysUserService.resetAdmin(sid, password, opUser);
            if (httpResult == null) {
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                return httpResult;
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "判断当前账套是否master账套")
    @ResponseBody
    @RequestMapping(value = "/isMaster.action", method = RequestMethod.POST)
    public HttpResult<Boolean> isMaster() {
        HttpResult<Boolean> hr = new HttpResult<>();
        try {
            hr.setData(DataSourceContextHolder.isMaster());
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "执行更新数据结构")
    @ResponseBody
    @RequestMapping(value = "/executeUpdateSchema.action", method = RequestMethod.POST)
    public HttpResult<Object> executeUpdateSchema() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            sysAccountSetService.executeUpdateSchema(sidList, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
